package com.cqc.paoclient.base;

import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.cqc.paoclient.util.ToastUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.greenrobot.eventbus.EventBus;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by cui on 2017/11/22.
 */

public abstract class BaseFragment<P extends BasePresenter> extends Fragment {

    protected P mPresenter;
    private Unbinder unbinder;
    private boolean isViewCreated = false;
    private boolean isVisibleToUser = false;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(getLayoutId(), container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        isViewCreated = true;
        mPresenter = getmPresenter();
        presenterSetView();
        initView();
        initData();
        loadData();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        lazyLoad();
    }

    protected void lazyLoad() {
        if (!isViewCreated || !isVisibleToUser) {
            return;
        } else {
            loadData();
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    protected abstract int getLayoutId();

    protected abstract P getmPresenter();

    protected abstract void presenterSetView();

    protected abstract void initView();

    protected abstract void initData();

    protected abstract void loadData();


    protected void showToat(String text) {
        ToastUtil.showLongToast(getContext(), text);
    }

    public void stopRefresh(SmartRefreshLayout refreshLayout) {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.finishRefresh();
        }
    }

    public void stopLoadMore(SmartRefreshLayout refreshLayout) {
        if (refreshLayout.isLoading()) {
            refreshLayout.finishLoadmore();
        }
    }

    public void startActivityWithIntent(Class clazz) {
        Intent intent = new Intent(getContext(), clazz);
        startActivity(intent);
    }
}
